// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include <zencore/zencore.h>

#include <zencore/compactbinary.h>
#include <zencore/compactbinarybuilder.h>

namespace zen {

/** Object rewrite helper

	This is meant to be used when you have a fully formed CbObject which you wish
	to rewrite. Since the compact binary format is not meant for in-place updates
	this involves scanning the object, copying the fields we want to keep and
	writing new versions of the fields we wish to keep.

	The Rewriter function accepts a reference to the CbObjectWriter which is being
	used to build the new version of the object and a reference to a field which is
	considered for copy or rewriting. If the function wants to rewrite a field then
	it'll use the writer to write a new field and then return `true`, otherwise just
	return `false` to have RewriteCbObject copy the field into the new object.
*/

void
RewriteCbObject(CbObjectWriter& CboWriter, CbObjectView InObj, Invocable<CbObjectWriter&, CbFieldView&> auto Rewriter)
{
	for (CbFieldView InnerField : InObj)
	{
		if (!Rewriter(CboWriter, InnerField))
		{
			CboWriter.AddField(InnerField.GetName(), InnerField);
		}
	}
}

CbObject
RewriteCbObject(CbObjectView InObj, Invocable<CbObjectWriter&, CbFieldView&> auto Rewriter)
{
	CbObjectWriter Writer;
	RewriteCbObject(Writer, InObj, Rewriter);
	return Writer.Save();
}

}  // namespace zen
